package com.test45_JUC;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;

/**
 * TransferQueue也是一个阻塞队列，JDK1.7引入的
 */
public class Demo21_TransferQueue {

    public static void main(String[] args) {
        test1();
    }

    /**
     * LinkedTransferQueue
     * 基于链表的方式实现，同时基于CAS操作形式实现了无阻塞的数据处理
     */
    public static void test1() {
        TransferQueue<String> queue = new LinkedTransferQueue<>();
        for (int x = 0; x < 10; x++) {
            final int temp = x;
            new Thread(() -> {
                for (int y = 0; y < 100; y++) {  // 持续生产
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        String msg = String.format("{ID = MUYAN - %d - %d}沐言科技：www.yootk.com", temp, y);
                        queue.put(msg);
                        System.out.printf("【%s】%s%n", Thread.currentThread().getName(), msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "YOOTK生产者-"+x).start();
        }

        for (int x = 0; x < 2; x++) {
            new Thread(() -> {
                while (true) {  // 持续性的通过队列取数据
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        System.err.printf("【%s】%s%n", Thread.currentThread().getName(), queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "YOOTK消费者-"+x).start();
        }
    }
}
